<template>
	<view class="content">
		<view class="taskDetail">
			<view class="detailTitle">
				下单信息
			</view>
			
			<view class="detailTxt">
				<text>服务单号</text><label>{{formData.orderNo}}</label>
			</view>
			<view class="detailTxt">
				<text>下单时间</text>{{formData.submitTime}}
			</view>
			<view class="detailTxt">
				<text>设备名称</text>{{formData.deviceName}} 2匹
			</view>
			<view class="detailTxt">
				<text>预约服务时间</text>{{formData.appointmentTimePeriod}}
			</view>
			<view class="detailTxt">
				<text>下单地址</text><label>{{formData.contactAddress}}</label>
			</view>
			<view class="detailTxt">
				<text>联系人</text>{{formData.contactName}}
			</view>
			<view class="detailTxt">
				<text>联系方式</text>{{formData.contactPhone}}
			</view>
			<view class="detailTxt">
				<text>预约内容</text>{{formData.appointmentType}}
			</view>
			<view class="detailTxt">
				<text>备注</text>{{formData.remark}}
			</view>
			<view class="detailTxt">
				<text>上传图片</text>
				<view class="imgInfo" v-if="formData.imageUrl != null">
					<image v-if="String(formData.imageUrl).includes(',')" @click="showImg(item)" v-for="(item,index) in formData.imageUrl.split(',')" :key="index" :src="item" mode=""></image>
					<image v-else @click="showImg(formData.imageUrl)" :src="formData.imageUrl" mode=""></image>
				</view>
			</view>
			
			<view class="detailTxt" v-if="formData.status > 2">
				<text>工单报告</text>
				<label @click="showDocument" style="color: blue;" v-if="formData.repairResult != null">查看工单</label>
			</view>
			
			<!-- <view class="detailTxt">
				<text>工单报告</text>
			</view> -->
		</view>
		
		<view class="imgWrap">
			<view class="imgTitle">
				服务照片
			</view>
			
			<view class="imgSubTile">
				服务前图片
			</view>
			<view class="imgList">
				<u-upload
					style="width:144rpx;height:144rpx;border-radius:12rpx;"
				   :fileList="beforeList"
				   :capture="['camera']"
				   @afterRead="afterRead"
				   @delete="deletePic"
				   :deletable="formData.status != 3"
				   :disabled="formData.status == 3 || optype == 2"
				   name="1"
				   multiple
				   :maxCount="10"
				 >
				 </u-upload>
			</view>
		</view>
		
		<view class="imgWrap">
			<view class="imgSubTile">
				服务中图片
			</view>
			<view class="imgList">
				<u-upload
					style="width:144rpx;height:144rpx;border-radius:12rpx;"
				   :fileList="fileList"
				   :capture="['camera']"
				   @afterRead="afterReadTwo"
				   @delete="deletePicTwo"
				   :deletable="formData.status != 3"
				   :disabled="formData.status == 3 || optype == 2"
				   name="2"
				   multiple
				   :maxCount="10"
				 >
				 </u-upload>
			</view>
		</view>
		
		<view class="imgWrap">
			<view class="imgSubTile">
				服务后图片
			</view>
			<view class="imgList">
				<u-upload
					style="width:144rpx;height:144rpx;border-radius:12rpx;"
				   :fileList="afterList"
				   :capture="['camera']"
				   @afterRead="afterReadThree"
				   @delete="deletePicThree"
				   :deletable="formData.status != 3"
				   :disabled="formData.status == 3 || optype == 2"
				   name="3"
				   multiple
				   :maxCount="10"
				 >
				 </u-upload>
			</view>
		</view>
		
		<view class="taskDetail">
			<view class="detailTitle">
				{{formData.serviceType == 0?'安装':formData.serviceType == 1?'维修':formData.serviceType == 2?'保养':'巡检'}}信息
			</view>
			<!-- <view class="detailTxt">
				<text>安装位置</text>23456789876543123
			</view> -->
			<view class="detailTxt">
				<text>{{formData.serviceType == 0?'安装':formData.serviceType == 1?'维修':formData.serviceType == 2?'保养':'巡检'}}日期</text>{{formData.submitTime}}
			</view>
			<view class="detailTxt">
				<text>设备名称</text>{{formData.deviceName}}
			</view>
			<view class="detailTxt">
				<text>设备品牌</text>
				<!-- {{formData.deviceName}} -->
			</view>
			<view class="detailTxt">
				<text>设备数量</text>{{formData.quantity}}
			</view>
			<view class="detailTxt">
				<text>设备型号</text>
				<!-- {{formData.deviceName}} -->
			</view>
			<view class="detailInputBox">
				<label>{{formData.serviceType == 0?'安装':formData.serviceType == 1?'维修':formData.serviceType == 2?'保养':'巡检'}}情况说明</label>
				<input type="text" v-model="completeForm.repairResult" placeholder="请输入情况说明" />
			</view> 
			<view class="detailInputBox">
				<label>{{formData.serviceType == 0?'安装':formData.serviceType == 1?'维修':formData.serviceType == 2?'保养':'巡检'}}备注说明</label>
				<input type="text" v-model="completeForm.remark" 
				:placeholder="'请输入'+(formData.serviceType == 0?'安装':formData.serviceType == 1?'维修':formData.serviceType == 2?'保养':'巡检')+'备注说明'" />
			</view>
		</view>	
		
		<view class="taskDetail" v-if="formData.partsUsageList && formData.partsUsageList.length > 0">
			<view class="detailTitle">
				工程量清单
			</view>
			
			<table class="baseTable">
				<tr>
					<th>序号</th>
					<th>材料名称</th>
					<th>规格</th>
					<th>小计</th>
				</tr>
				
				<tbody>
					<tr v-for="(item,index) in formData.partsUsageList" :key="index">
						<td>{{index + 1}}</td>
						<td>{{item.partsName}}</td>
						<td>{{item.specification}}</td>
						<td>{{item.quantity}}</td>
					</tr>
				</tbody>
			</table>
			
			<block v-if="optype != 2">
				<view class="addBox" @click="addPurchase" v-if="formData.status != 3">
					＋添加清单项
				</view>
			</block>
			
		</view>
		
		<view class="taskDetail">
			<view class="detailTitle">
				参与人员
			</view>
			<view class="detailTxt" v-for="(item,index) in formData.masterList" :key="index">
				<text>{{item.masterType == 1?'主要负责人':item.masterType == 2?'辅助人员':''}}</text>{{item.masterName}}
			</view>
			<!-- <view class="detailTxt">
				<text></text>张师傅
			</view> -->
		</view>
		
		<block v-if="optype != 2">
			<view class="baseBottom" v-if="formData.status != 3">
				<text class="btn1" @click="showBei">领用备件</text>
				<text class="btn2" @click="signUpp" v-if="formData.arrivalTime == null">签到</text>
				<text class="btn2" v-else @click="completeTask">完成任务</text>
			</view>
		</block>
		
		<jushi-watermark-vue ref="watermark" @callback="watermarkCallback" fontColor="red"></jushi-watermark-vue>
		
		<purchaseInfo ref="purchase"></purchaseInfo>
		<useParts @showForm="showForm" ref="useParts"></useParts>
		
	</view>
</template>

<script>
	import purchaseInfo from '@/components/purchase.vue';
	import useParts from '@/components/useParts.vue';
	import { getTeacherOrderDetail, teacherSingn, completeOrder, updateConfirmStatus } from '@/api/login.js';
	import moment from 'moment';
	import baseUrl  from '@/util/config.js';
	import QQMapWX from "../../util/qqmap-wx-jssdk.js";
	export default {
		components:{
			purchaseInfo, useParts
		},
		data() {
			return {
				optype: '',
				fileList: [],
				afterList: [],
				beforeList: [],
				formData:{},
				orderId: '',
				imgType: '',
				completeForm:{
					leaveTime: '',
					afterImageUrls: '',
					beforeImageUrls: '',
					middleImageUrls: '',
					repairResult: '',
					remark: ''
				}
			}
		},
		onLoad(opt) {
			this.orderId = opt.idd;
			this.optype = opt.optype == undefined?'':opt.optype;
			this.getDetail(opt.idd);
		},
		onShareAppMessage() {
			
		},
		methods: {
			// 预览图片
			showImg(val){
				console.log(val);
				uni.previewImage({
					urls: [val]
				});
			},
			// 删除图片
			deletePic(val,type){
				if(type == 1) {
					this.fileList.splice(val.index,1);
				} else if(type == 2) {
					this.afterList.splice(val.index,1);
				} else {
					this.beforeList.splice(val.index,1);
				}
			},
			deletePicTwo(val) {
				this.deletePic(val,1);
			},
			deletePicThree(val) {
				this.deletePic(val,2);
			},
			afterReadTwo(event){
				this.afterRead(event, 1);
			},
			afterReadThree(event){
				this.afterRead(event, 2);
			},
			addImages(filePaths) {// 添加图片
				console.log(filePaths,'===');
				var texts = ["时间：" + moment().format('YYYY-MM-DD HH:mm:ss'), "地址：" + this.formData.contactAddress]
				// texts.push("水印时间：" + this.getNowTime())
				// 添加水印
				this.$refs.watermark.addWaterMark({
					filePath: filePaths.url,
					texts: texts
				})
			},
			watermarkCallback(filePath) {
				uni.uploadFile({
					url: baseUrl.baseUrl + '/common/upload',
					filePath: filePath,
					name: 'file',
					header: {
						Authorization: 'Bearer ' + uni.getStorageSync('userToken')
					},
					formData: {
						frontFileType: 'picture'
					},
					success: res => {
						var jsurl = JSON.parse(res.data);
						if (jsurl.code != 200) {
							return uni.$u.toast(jsurl.msg);
						}
						if(jsurl.url != '') {
							if(this.imgType == 1) {
								let objj = {
									url: jsurl.url
								};
								this.fileList.push(objj);
							} else if(this.imgType == 2) {
								let objj = {
									url: jsurl.url
								};
								this.afterList.push(objj);
							} else {
								let objj = {
									url: jsurl.url
								};
								this.beforeList.push(objj);
							}
							
						} else {
							uni.$u.toast('上传错误!');
						}
					}
				});
			},	
			afterRead(event,type){
				if(this.formData.arrivalTime == null) {
					return uni.$u.toast('请先签到!');
				}
				this.imgType = type;
				let wenList = event.file;
				wenList.forEach(item=>{
					this.addImages(item);
				})
			},
			showBei(){
				const pmm = {
					projectId: this.formData.projectId,
					orderId: this.formData.id
				}
				this.$refs['useParts'].showInfo(pmm);
			},
			getDetail(idd) {
				getTeacherOrderDetail(idd).then(res=>{
					if(res.code == 200) {
						this.formData = res.data;
						if(res.data.status == 3) {
							if(String(res.data.repairResult).includes('工单报告')){
								this.completeForm.repairResult = String(res.data.repairResult).split('工单报告')[0];
							} else {
								this.completeForm.repairResult = res.data.repairResult;
							}
							this.completeForm.remark = res.data.remark;
							// 展示服务前后图片
							if(res.data.beforeImageUrl != null) {
								if(res.data.beforeImageUrl.includes(',')) {
									let imgArr = res.data.beforeImageUrl.split(',');
									let newArr = [];
									imgArr.forEach(item=>{
										let objj = {
											url: item
										};
										newArr.push(objj)
									});
									this.beforeList = newArr;
								} else {
									let objj = {
										url: res.data.beforeImageUrl
									};
									this.beforeList.push(objj);
								}
							}
							if(res.data.middleImageUrl != null) {
								if(res.data.middleImageUrl.includes(',')) {
									let imgArr = res.data.middleImageUrl.split(',');
									let newArr = [];
									imgArr.forEach(item=>{
										let objj = {
											url: item
										};
										newArr.push(objj)
									});
									this.fileList = newArr;
								} else {
									let objj = {
										url: res.data.middleImageUrl
									};
									this.fileList.push(objj);
								}
							}
							if(res.data.afterImageUrl != null) {
								if(res.data.afterImageUrl.includes(',')) {
									let imgArr = res.data.afterImageUrl.split(',');
									let newArr = [];
									imgArr.forEach(item=>{
										let objj = {
											url: item
										};
										newArr.push(objj)
									});
									this.afterList = newArr;
								} else {
									let objj = {
										url: res.data.afterImageUrl
									};
									this.afterList.push(objj);
								}
							}
							console.log(this.beforeList)
						}
					} else {
						uni.$u.toast(res.msg);
					}
				})
			},
			// 完成任务
			completeTask(){
				// if(this.formData.partsUsageList.length == 0) {
				// 	return uni.$u.toast('请先领用备件!');
				// }
				if(this.beforeList.length == 0) {
					return uni.$u.toast('请上传服务前图片!');
				}
				if(this.fileList.length == 0) {
					return uni.$u.toast('请上传服务中图片!');
				}
				if(this.afterList.length == 0) {
					return uni.$u.toast('请上传服务后图片!');
				}
				if(this.completeForm.repairResult == '') {
					return uni.$u.toast('请输入安装情况说明!');
				}
				uni.showModal({
				    title: '提示',
				    content: '确定要完成任务吗?',
				    success: res => {
				        if (res.confirm) {
							if(this.beforeList.length > 0) {
								let urlArr = [];
								this.beforeList.forEach(item=>{
									urlArr.push(item.url);
								});
								this.completeForm.beforeImageUrls = urlArr.toString();
							} else {
								this.completeForm.beforeImageUrls = '';
							}	
							if(this.fileList.length > 0) {
								let urlArr = [];
								this.fileList.forEach(item=>{
									urlArr.push(item.url);
								});
								this.completeForm.middleImageUrls = urlArr.toString();
							} else {
								this.completeForm.middleImageUrls = '';
							}
							if(this.afterList.length > 0) {
								let urlArr = [];
								this.afterList.forEach(item=>{
									urlArr.push(item.url);
								});
								this.completeForm.afterImageUrls = urlArr.toString();
							} else {
								this.completeForm.afterImageUrls = '';
							}
				            this.completeForm.leaveTime = moment().format('YYYY-MM-DD HH:ss:mm');
				            console.log(this.completeForm);
				            completeOrder(this.formData.id, JSON.stringify(this.completeForm)).then(res=>{
				            	if(res.code == 200) {
									updateConfirmStatus({orderId:this.orderId,confirmStatus: 1}).then(resbb=>{
										uni.$u.toast('操作成功!');
										setTimeout(()=>{
											uni.switchTab({
												url:'/pages/engineer/index'
											});
										},500);
									});
								} else {
									uni.$u.toast(res.msg);
								}
				            });
				        } else if (res.cancel) {
				            
				        }
				    }
				});
				
			},
			// 签到
			signUpp(){
				let qqmapsdk;
				qqmapsdk = new QQMapWX({
					key: "OUYBZ-JF2HP-Q5ADA-VAJQV-EAKVT-UIFKT"
				});
				uni.getLocation({
					success: (res) => {
						qqmapsdk.reverseGeocoder({
							//根据经纬度获取地址信息 
							location: {
								latitude: res.latitude,
								longitude: res.longitude
							},
							success: ress => {
								console.log(ress.result.address,'===位置信息====');
								console.log(this.formData.contactAddress);
								// if(ress.result.address != this.formData.contactAddress) {
								// 	return uni.$u.toast('当前位置和客户预定的位置不一致!');
								// }
								const pmm = {
									arrivalTime: moment().format('YYYY-MM-DD HH:ss:mm')
								}
								uni.showLoading({
									title: '签到中...'
								});
								teacherSingn(this.formData.id,pmm).then(res=>{
									uni.hideLoading();
									if(res.code == 200) {
										uni.$u.toast('签到成功!');
										// 刷新表单
										this.getDetail(this.orderId);
									} else {
										uni.$u.toast(res.msg);
									}
								})
							}
						})
					},
				});	
			},
			// 刷新表单
			showForm(){
				this.getDetail(this.orderId);
			},
			// 添加备件清单
			addPurchase(){
				this.showBei();
			},
			showDocument(){
				if(!String(this.formData.repairResult).includes('http')) {
					return uni.$u.toast('文件格式不正确，无法打开!');;
				}
				let openUrl = 'http' + String(this.formData.repairResult).split('http')[1];
				uni.downloadFile({
				  url: openUrl,
				  success(res) {
					const tempFilePath = res.tempFilePath;
					uni.openDocument({
					  filePath: tempFilePath,
					  fileType: 'pdf',
					  success: function () {
						console.log('成功打开 PDF');
					  },
					  fail: function (err) {
						console.error('打开失败:', err);
					  }
					});
				  },
				  fail(err) {
					console.error('下载失败:', err);
				  }
				});
			
			},
		}
	}
</script>

<style lang="scss" scoped>
.content{
	background-color:#f5f5f5;padding:24rpx;
	.baseBottom{
		margin:0 0 68rpx;@include flx;justify-content: space-between;
		text{
			display: block;width: 336rpx;background: #E6E6E7;border-radius: 40rpx;text-align: center;height:80rpx;
			@include baseFont(30rpx,#17181B,80rpx);
		}
		.btn2{
			background: linear-gradient( 90deg, #588FFF 0%, #3671E9 100%);color:#fff;font-weight:500;
		}
	}
	.imgWrap{
		border-radius:12rpx;background-color:#fff;margin-bottom:16rpx;padding:24rpx 32rpx;
		.imgTitle{
			@include baseFont(28rpx,#000,44rpx);font-weight:500;margin-bottom:12rpx;
		}
		.imgSubTile{
			@include baseFont(28rpx,#262626,36rpx);margin-bottom:22rpx;
		}
		.imgList{
			@include flx;flex-wrap: wrap;
			image{
				display: block;width:192rpx;height:192rpx;border-radius:8rpx;margin-bottom:20rpx;margin-right:30rpx;
			}
			image:nth-of-type(3n){
				margin-right:0;
			}
		}
	}
	.taskDetail{
		border-radius:12rpx;background-color:#fff;margin-bottom:16rpx;padding:24rpx 32rpx;
		.detailTitle{
			@include baseFont(28rpx,#000,44rpx);font-weight:500;margin-bottom:12rpx;
		}
		.addBox{
			height: 64rpx;width:100%;margin-top:14rpx;
			background: #FFFFFF;@include baseFont(28rpx,#3671E9,64rpx);
			border-radius: 8rpx;text-align: center;
			border: 2rpx solid rgba(54,113,233,0.6);
		}
		.baseTable {
		  width: 100%; /* 或者指定一个具体的宽度 */
		  border-collapse: collapse; /* 使边框合并 */
		  
		  tr{
			  display: flex;flex-direction: row;
			  th, td {
				width: 25%;
			    text-align: center; /* 文本左对齐 */
			  }
			  th{
			  	@include baseFont(26rpx,#999,88rpx);background-color: #F0F0F0;
			  }
			  td{
				  @include baseFont(26rpx,#333,88rpx);border-bottom:2rpx solid #F0F0F0;
			  }
		  }
		  
		}
		.detailTxt{
			@include baseFont(28rpx,#333,40rpx);@include flx;margin-bottom:12rpx;
			text{
				display: block;color:#666;width:176rpx;
			}
			image{
				display: block;width:124rpx;height:124rpx;border-radius:8rpx;
			}
			label{
				display: block;
			}
		}
		.detailInputBox{
			margin-bottom:12rpx;
			label{
				display: block;@include baseFont(28rpx,#333,40rpx);margin-bottom:12rpx;
			}
			input{
				display: block;background-color:#F6F6F6;height:80rpx;@include baseFont(28rpx,#333,80rpx);padding:0 20rpx;
			}
		}
	}
}
</style>
